package movieGandalf.GUI;

import java.math.BigInteger;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;

import movieGandalf.BL.ObjectsBL;
import movieGandalf.BL.ObjectsMYSQLBL;
import movieGandalf.GUI.GUIManager.StatusEnum;
import movieGandalf.logicGuiConnection.Movie;
import movieGandalf.logicGuiConnection.User;

// This class is used to encapsulate the links in the movie 
// table and the the movie itself
public class LinkAdapter extends SelectionAdapter {
	private static final String CONNECTION_ERR = "Error while trying to check value, please try again later";
	private User user;

	public LinkAdapter(User user) {
		this.user=user;
	}

	@Override
	public void widgetSelected(SelectionEvent arg0) {
		ShowMovie(arg0.text, null,
				(Composite) arg0.widget.getData("composite"));
	}

	// Display the movie in a new window
	void ShowMovie(final String charName, final BigInteger id,
			final Composite composite) {
		//TODO get movie detail: done not debugged
		final ObjectsBL bl = new ObjectsMYSQLBL();

		Thread newThread = new Thread(new Runnable() {
			@Override
			public void run() {
				
				// Get character data from DB
				final Movie newMov = bl.getMovie(id);
				Runnable runInGui;
				if (newMov == null) {
					runInGui = new Runnable() {

						@Override
						public void run() {
							GUIManager.sendStatus(CONNECTION_ERR,
									StatusEnum.ERROR);
						}
					};
				} else {
					runInGui = new Runnable() {

						@Override
						public void run() {
							Shell otherMovieShell = new Shell(composite
									.getShell(), SWT.DIALOG_TRIM);
							otherMovieShell.setSize(composite.getShell()
									.getSize());
							otherMovieShell.setLayout(new FillLayout());
							new MoviePage(otherMovieShell, SWT.NONE,
									newMov, user);
							otherMovieShell.setText(newMov.getName());
							otherMovieShell.open();
							otherMovieShell.layout();
						}
					};
				}
				GUIManager.sendToMainThread(runInGui);
			}
		});
		newThread.start();
	}
}
